package org.zjx.db;

import org.zjx.common.bean.Server;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ServerDB {
    private static boolean isTableCreated = false;  // Flag to ensure the table is only created once
    private final SQLiteHelper dbHelper;

    public ServerDB() {
        dbHelper = SQLiteHelper.getSingleton();
        // Only create the table once when the instance is first created
        if (!isTableCreated) {
            createTable();
            isTableCreated = true;
        }
    }

    // Create table for Server
    public void createTable() {
        String createTable = "CREATE TABLE IF NOT EXISTS server (\n"
                + "    id INTEGER PRIMARY KEY AUTOINCREMENT,\n"
                + "    masterServerName TEXT NOT NULL,\n"
                + "    masterLocation TEXT,\n"
                + "    serverName TEXT NOT NULL,\n"
                + "    serverLocation TEXT\n"
                + ");";
        dbHelper.createTable(createTable);
    }

    // Insert a Server record
    public void insert(Server server) {
        String sql = "INSERT INTO server(masterServerName, masterLocation, serverName, serverLocation) VALUES(?, ?, ?, ?)";
        Object[] params = {
                server.getMasterServerName(),
                server.getMasterLocation(),
                server.getServerName(),
                server.getServerLocation()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Update a Server record
    public void update(Server server) {
        String sql = "UPDATE server SET masterServerName = ?, masterLocation = ?, serverName = ?, serverLocation = ? WHERE id = ?";
        Object[] params = {
                server.getMasterServerName(),
                server.getMasterLocation(),
                server.getServerName(),
                server.getServerLocation(),
                server.getId()
        };
        dbHelper.executeUpdate(sql, params);
    }

    // Delete a Server record by ID
    public void deleteById(int id) {
        String sql = "DELETE FROM server WHERE id = ?";
        Object[] params = {id};
        dbHelper.executeUpdate(sql, params);
    }

    // Find Server by ID
    public Server findById(int id) {
        String sql = "SELECT * FROM server WHERE id = ?";
        Object[] params = {id};
        List<Server> servers = dbHelper.executeQuery(sql, params, Server.class);
        if (servers.isEmpty()) return null;
        return servers.get(0);
    }

    // Find Server by Name
    public Server findByName(String serverName) {
        String sql = "SELECT * FROM server WHERE serverName = ?";
        Object[] params = {serverName};
        List<Server> servers = dbHelper.executeQuery(sql, params, Server.class);
        if (servers.isEmpty()) return null;
        return servers.get(0);
    }

    // Get all Servers
    public List<Server> findAll() {
        String sql = "SELECT * FROM server";
        Object[] params = {};
        return dbHelper.executeQuery(sql, params, Server.class);
    }

    // Paginated query for Servers
    public Map<String, Object> findAllWithPagination(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;

        String sql = "SELECT * FROM server LIMIT ? OFFSET ?";
        Object[] params = {pageSize, offset};
        List<Server> servers = dbHelper.executeQuery(sql, params, Server.class);

        String countSql = "SELECT COUNT(*) FROM server";
        Object[] countParams = {};
        List<Integer> totalRecordsList = dbHelper.executeQuery(countSql, countParams, Integer.class);
        int totalRecords = totalRecordsList.isEmpty() ? 0 : totalRecordsList.get(0);

        int totalPages = (int) Math.ceil((double) totalRecords / pageSize);

        Map<String, Object> result = new HashMap<>();
        result.put("serverList", servers);
        result.put("totalRecords", totalRecords);
        result.put("totalPages", totalPages);
        result.put("currentPage", pageNum);

        return result;
    }

    // Clear all Server data
    public void clearData() {
        dbHelper.clearData("server");
    }

    // Drop the Server table
    public void dropTable() {
        dbHelper.dropTable("server");
    }
}
